"""
本机摄像头HTTP流服务器
提供MJPEG格式的摄像头视频流
"""

import cv2
import threading
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
import socketserver

class CameraHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/stream':
            self.send_response(200)
            self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=frame')
            self.send_header('Cache-Control', 'no-cache')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            
            # 打开摄像头
            cap = cv2.VideoCapture(0)  # 0表示默认摄像头
            cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
            cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
            cap.set(cv2.CAP_PROP_FPS, 30)
            
            try:
                while True:
                    ret, frame = cap.read()
                    if not ret:
                        break
                    
                    # 编码为JPEG
                    _, buffer = cv2.imencode('.jpg', frame, [cv2.IMWRITE_JPEG_QUALITY, 80])
                    frame_bytes = buffer.tobytes()
                    
                    # 发送MJPEG帧
                    self.wfile.write(b'--frame\r\n')
                    self.wfile.write(b'Content-Type: image/jpeg\r\n')
                    self.wfile.write(f'Content-Length: {len(frame_bytes)}\r\n\r\n'.encode())
                    self.wfile.write(frame_bytes)
                    self.wfile.write(b'\r\n')
                    
                    time.sleep(1/30)  # 30 FPS
                    
            except Exception as e:
                print(f"摄像头流错误: {e}")
            finally:
                cap.release()
                
        elif self.path == '/':
            # 简单的测试页面
            self.send_response(200)
            self.send_header('Content-Type', 'text/html; charset=utf-8')
            self.end_headers()
            html = """
            <!DOCTYPE html>
            <html>
            <head>
                <title>本机摄像头流</title>
                <meta charset="utf-8">
            </head>
            <body>
                <h1>本机摄像头HTTP流服务</h1>
                <p>摄像头流地址: <a href="/stream">http://localhost:8081/stream</a></p>
                <img src="/stream" style="max-width: 640px; border: 1px solid #ccc;">
            </body>
            </html>
            """
            self.wfile.write(html.encode('utf-8'))
        else:
            self.send_response(404)
            self.end_headers()

def start_camera_server():
    server = HTTPServer(('localhost', 8081), CameraHandler)
    print("本机摄像头HTTP流服务已启动")
    print("访问地址: http://localhost:8081/")
    print("流地址: http://localhost:8081/stream")
    print("按 Ctrl+C 停止服务")
    
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\n正在停止服务...")
        server.shutdown()

if __name__ == "__main__":
    start_camera_server()